package com.yuyou.fn.controller;

import com.yuyou.fn.common.service.ISmsService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wens on 16-11-30.
 */
@Controller
public class SmsApiController {

    @Resource
    private ISmsService smsService;

    @ApiOperation(value = "发送短信验证码" )
    @RequestMapping(value = { "/api/sms/sendCode" ,"/api/sms/code" } ,method = { RequestMethod.GET ,RequestMethod.POST })
    @ResponseBody
    public ReturnResult sendCode(@RequestParam("phoneNo") String phoneNo) {
        boolean ok = smsService.sendCode(phoneNo);
        if (ok) {
            return ReturnResult.success("发送成功");
        } else {
            return ReturnResult.fail("发送失败");
        }
    }

    @ApiOperation(value = "验证短信验证码" )
    @RequestMapping(value = "/api/sms/validCode" ,method = { RequestMethod.GET ,RequestMethod.POST } )
    @ResponseBody
    public ReturnResult validCode( @RequestParam("phoneNo" ) String phoneNo ,@ApiParam(value = "短信验证码",required = true) @RequestParam("code") String code  ) {

        boolean ok = smsService.validate(phoneNo , code );
        if (ok) {
            String ticket  = Base64.encodeBase64URLSafeString(code.getBytes());
            Map<String,Object> ret  = new HashMap<>();
            ret.put("ticket" , ticket );
            return ReturnResult.success(ret);
        } else {
            return ReturnResult.fail("验证码校验失败");
        }
    }
}
